package com.tcoding.client.event;

import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 唐全成
 * @Date: 2022/6/13 11:42
 * @description
 **/
@Component
public class CustomEventManager {


    /**
     * 记录发布的事件和对该事件进行了监听的监听器
     *
     * */
    private static Map<String, List<CustomEventListener>> map=new HashMap<>();


    /**
     * 注册监听
     * @param listener
     */
    public static void addListener(CustomEventListener listener){
        //获取泛型类
        Class arg = (Class)((ParameterizedType) listener.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
        String name=arg.getName();
        if(!map.containsKey(name)){
            map.put(name,new ArrayList<>());
        }
        map.get(name).add(listener);
    }

    /**
     * 发布事件
     * @param event
     */
    public static void publish(CustomEvent event) {

        if (map.containsKey(event.getClass().getName())) {
            List<CustomEventListener> list = map.get(event.getClass().getName());
            for (CustomEventListener listener : list) {
                try {
                    listener.handler(event);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
